package com.itboye.sunsun.luntan;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CursorAdapter;
import android.widget.FrameLayout.LayoutParams;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;

import com.itboye.homesensen.alert.ByAlert;
import com.itboye.luntan.web.FlowLayout;
import com.itboye.sunsun.adapter.LunTanSouSuoSearAdapter;
import com.itboye.sunsun.adapter.LunTanSouSuoSearTieziAdapter;
import com.itboye.sunsun.beans.LuntanTieziSouBeans;
import com.itboye.sunsun.beans.LuntanTieziSouBeans.LunTanTieziSearBean;
import com.itboye.sunsun.beans.WeChatBean;
import com.itboye.sunsun.beans.WeChatBean.WeChaReMenBean;
import com.itboye.sunsun.custome.LunTanEdittext;
import com.itboye.sunsun.custome.MyListView;
import com.itboye.sunsun.custome.XListView;
import com.itboye.sunsun.custome.XListView.IXListViewListener;
import com.itboye.sunsun.db.RecordSQLiteOpenHelper;
import com.itboye.sunsun.network.HttpRequest;
import com.itboye.sunsun.support.BaseActivity;
import com.itboye.sunsun.volley.MyJsonRequest;
import com.itboye.sunsun.volley.XErrorListener;
import com.itboye.sunsun.volley.XRequestListener;
import com.itboye.sunsunhome.R;

/**
 * 搜索
 * 
 * @author 余 焱
 * 
 */
public class LunTanSearTableActivity extends BaseActivity implements
		OnClickListener, IXListViewListener {

	MyListView listView;
	XListView listViewdb;

	private LunTanEdittext et_search;
	private BaseAdapter adapter;

	private TextView delete;
	PopupWindow popupWindow;
	private RelativeLayout realyouttitl;
	private TextView spinner, tvLutanSize;
	private int num = 1;// 1表示通过帖子名称搜索 2表示通过发帖人昵称进行搜索

	List<WeChaReMenBean> channelList = new ArrayList<WeChaReMenBean>();
	List<LunTanTieziSearBean> list = new ArrayList<LunTanTieziSearBean>();

	private RelativeLayout re_nodate;
	private ImageView spanner_icon;
	FlowLayout tagGroup;
	RelativeLayout realyoutTop;
	TextView[] childView;
	List<WeChaReMenBean> wordQueryModels = new ArrayList<WeChaReMenBean>();
	private LinearLayout linLuntan, linLutanListview;

	private int page_num = 1;// 页码数

	private int isnum;
	private int i;
	private ImageView back;

	private ImageView tv_clear;
	private RecordSQLiteOpenHelper helper = new RecordSQLiteOpenHelper(this);;
	private SQLiteDatabase db;
	private BaseAdapter dbadapter;

	LuntanSearAdapter searAdapter;
	MyGridView otherGridView;

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.itboye.sunsun.support.BaseActivity#onCreate(android.os.Bundle)
	 */
	@Override
	@SuppressLint("InlinedApi")
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		setContentView(R.layout.activity_luntan_search);
		setStatusBarColor(R.color.home_blue);
		re_nodate = (RelativeLayout) findViewById(R.id.re_nodate);
		re_nodate.setVisibility(View.GONE);
		listViewdb.setXListViewListener(this);
		listViewdb.setPullLoadEnable(true);
		listViewdb.setPullRefreshEnable(true);
		et_search.addTextChangedListener(textWatcher);
		otherGridView = (MyGridView) findViewById(R.id.otherGridView);

		searAdapter = new LuntanSearAdapter(LunTanSearTableActivity.this,
				wordQueryModels);

		otherGridView.setAdapter(searAdapter);

		otherGridView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.putExtra("fid", wordQueryModels.get(position).getFid());
				setResult(104, intent);
				finish();
			}
		});

		PublicReMen();
		popupWindow = new PopupWindow();
		// 清空搜索历史
		tv_clear.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				deleteData();
				queryData("");
			}
		});

		// listview点击事件
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				TextView textView = (TextView) view
						.findViewById(R.id.luntanName);
				String name = textView.getText().toString();
				et_search.setText(name);
			}
		});
		// listview点击事件
		listViewdb.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				// position--;

				Intent intent = new Intent(LunTanSearTableActivity.this,
						TieZiDetailActivity.class);
				LunTanTieziSearBean bean = list.get(position - 1);
				intent.putExtra("fid", bean.getFid());
				intent.putExtra("tid", bean.getTid());
				startActivity(intent);
				finish();
			}
		});

		// 插入数据，便于测试，否则第一次进入没有数据怎么测试呀？
		Date date = new Date();
		long time = date.getTime();

		// 第一次进入查询所有的历史记录

		if (et_search.getText().toString().equals("")
				|| et_search.getText().toString() == null) {
			try {
				queryData("");
			} catch (Exception e) {
				// TODO: handle exception
			}
		} else {
			insertData(et_search.getText().toString());
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {

		case R.id.back:
			finish();
			break;

		case R.id.realyouttitl:

			PuPoWindow(v);
			break;

		case R.id.re_shuizu_search:// 帖子

			spinner.setText("按标题");
			num = 1;
			popupWindow.dismiss();

			break;
		case R.id.re_shuizu_message:// 用户

			spinner.setText("按作者");
			num = 2;
			popupWindow.dismiss();

			break;
		case R.id.delete:// 搜索

			boolean hasData = hasData(et_search.getText().toString().trim());
			if (!hasData) {
				if (et_search.getText().toString().equals("")
						|| et_search.getText().toString() == null) {
					try {
						queryData("");
					} catch (Exception e) {
						// TODO: handle exception
					}
				} else {
					insertData(et_search.getText().toString().trim());
				}

			}

			if (num == 1) {
				list.clear();
				pullUp();

				adapter = new LunTanSouSuoSearTieziAdapter(list,
						LunTanSearTableActivity.this);
				listViewdb.setAdapter(adapter);
				// tvLutanSize.setText("共搜索到" + adapter.getItem(list.size())
				// + "条数据");
				// adapter.notifyDataSetChanged();
			} else {
				list.clear();
				pullUp();
				adapter = new LunTanSouSuoSearAdapter(list,
						LunTanSearTableActivity.this);
				listViewdb.setAdapter(adapter);
				// tvLutanSize.setText("共搜索到" + adapter.getItem(list.size())
				// + "条数据");
				// adapter.notifyDataSetChanged();

			}
			break;
		default:
			break;
		}
	}

	TextWatcher textWatcher = new TextWatcher() {

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {
			// TODO Auto-generated method stub
			System.out.println("<><><><<<<<<<<>>>>>>>>>>>>>>>>>>onTextChanged"
					+ et_search.getText().toString());
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			System.out
					.println("<><><><<<<<<<<>>>>>>>>>>>>>>>>>>beforeTextChanged"
							+ et_search.getText().toString());
		}

		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			System.out
					.println("<><><><<<<<<<<>>>>>>>>>>>>>>>>>>afterTextChanged"
							+ et_search.getText().toString());
			// if (s.toString().trim().length() == 0) {
			// tv_tip.setText("搜索历史");
			// } else {
			// tv_tip.setText("搜索结果");
			// }
			String tempName = et_search.getText().toString();
			// 根据tempName去模糊查询数据库中有没有数据
			queryData(tempName);
		}
	};

	/**
	 * 论坛搜索类型切换
	 * 
	 * @param v
	 */
	public void PuPoWindow(View v) {

		View view = LayoutInflater.from(this).inflate(
				R.layout.item_luntan_sousuo, null);
		RelativeLayout re_shuizu_search = (RelativeLayout) view
				.findViewById(R.id.re_shuizu_search);
		RelativeLayout re_shuizu_message = (RelativeLayout) view
				.findViewById(R.id.re_shuizu_message);

		re_shuizu_search.setOnClickListener(this);
		re_shuizu_message.setOnClickListener(this);
		popupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		popupWindow.setOutsideTouchable(true);
		popupWindow.setBackgroundDrawable(new BitmapDrawable());
		popupWindow.showAsDropDown(v);
	}

	/**
	 * 搜索帖子
	 */
	private void pullUp() {
		// 设置num默认为1

		showProgressDialog("搜索中，请稍后", true);
		MyJsonRequest.Builder<LuntanTieziSouBeans> builder = new MyJsonRequest.Builder<LuntanTieziSouBeans>()
				.apiVer("100").typeKey("BY_BbsFavorite_searchcard")
				.param("ttype", num + "")
				.param("name", et_search.getText().toString())
				.param("page_no", page_num).param("page_size", 8)
				.requestListener(new XRequestListener<LuntanTieziSouBeans>() {

					@Override
					public void onResponse(final LuntanTieziSouBeans bean) {
						// listView.setVisibility(View.GONE);
						// linLuntan.setVisibility(View.GONE);
						// list.clear();
						if (page_num == 1) {

							list.clear();

						}
						if (et_search.getText().toString().isEmpty()) {
							ByAlert.alert("输入不能为空");
							realyoutTop.setVisibility(View.GONE);
							closeProgressDialog();
							return;
						}
						if (bean.getCount() > 0 && bean.getList() != null) {

							realyoutTop.setVisibility(View.VISIBLE);

							tvLutanSize.setText("共搜索到" + bean.getCount()
									+ "条数据");
							re_nodate.setVisibility(View.GONE);

							linLuntan.setVisibility(View.GONE);
							linLutanListview.setVisibility(View.VISIBLE);
							list.addAll(bean.getList());
							adapter.notifyDataSetChanged();

						} else if (list == null) {
							linLuntan.setVisibility(View.GONE);
							re_nodate.setVisibility(View.VISIBLE);
							ByAlert.alert("没有找到理想的数据....");
						} else if (list.size() <= 0) {
							linLuntan.setVisibility(View.GONE);
							re_nodate.setVisibility(View.VISIBLE);
							ByAlert.alert("没有找到理想的数据....");
						}
						try {
							closeProgressDialog();
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						// onPullDownError(adapter, xlistview, exception,
						// code,p[]\l;
						listViewdb.stopLoadMore();
						System.out.println("" + msg);
						// msg);
						try {
							closeProgressDialog();

						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				});

		MyJsonRequest<LuntanTieziSouBeans> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	private void PublicReMen() {
		// 设置num默认为1
		MyJsonRequest.Builder<WeChatBean> builder = new MyJsonRequest.Builder<WeChatBean>()
				.typeKey("BY_BbsUserCenter_hotRecommend").apiVer("100")
				.requestListener(new XRequestListener<WeChatBean>() {

					@Override
					public void onResponse(final WeChatBean bean) {
						wordQueryModels.clear();
						if (bean.getCount() > 0) {
							wordQueryModels.addAll(bean.getList());
							onTextVIew();

						}

					}
				}).errorListener(new XErrorListener() {

					@Override
					public void onErrorResponse(Exception exception, int code,
							String msg) {
						// onPullDownError(adapter, xlistview, exception,
						// code,p[]\l;
						listViewdb.stopLoadMore();
						System.out.println("" + msg);
						// msg);
					}
				});

		MyJsonRequest<WeChatBean> request = builder.build();
		HttpRequest.getDefaultRequestQueue().add(request);
	}

	public void onTextVIew() {

		childView = new TextView[wordQueryModels.size()];
		for (i = 0; i < wordQueryModels.size(); i++) {
			tagGroup = (FlowLayout) findViewById(R.id.tagGroup);
			View view = LayoutInflater.from(LunTanSearTableActivity.this)
					.inflate(R.layout.textview, null);
			TextView textView = (TextView) view.findViewById(R.id.text);
			ImageView img_del = (ImageView) view.findViewById(R.id.img_del);
			img_del.setVisibility(View.GONE);
			tagGroup = (FlowLayout) findViewById(R.id.tagGroup);
			textView.setText(wordQueryModels.get(i).getName() + "");
			textView.setGravity(Gravity.CENTER);
			textView.setTextColor(getResources().getColor(R.color.black));
			// textView.setBackgroundDrawable(getResources()));
			textView.setTag(i);
			childView[i] = textView;
			childView[i].setTag(i);
			android.widget.RelativeLayout.LayoutParams lP = new android.widget.RelativeLayout.LayoutParams(
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT,
					android.widget.RelativeLayout.LayoutParams.WRAP_CONTENT);
			lP.setMargins(10, 10, 10, 10);
			tagGroup.addView(view, lP);

			childView[i].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					// et_search.setText();

					String postion = childView[Integer.parseInt(v.getTag() + "")]
							.getText().toString();
					int postionfid = Integer.parseInt(postion);
					Intent intent = new Intent(LunTanSearTableActivity.this,
							LunTanDetailActivity.class);
					intent.putExtra("ffid", wordQueryModels.get(i).getFid());
					startActivity(intent);
					System.out.println("IIIIIIIIIIIIIIIIII"
							+ wordQueryModels.get(i).getFid());
					finish();

				}
			});

		}
	}

	@Override
	public void onRefresh() {
		page_num = 1;
		pullUp();
		stopload();
	}

	@Override
	public void onLoadMore() {
		page_num++;
		pullUp();
		stopload();

	}

	public void stopload() {
		listViewdb.stopLoadMore();
		listViewdb.stopRefresh();
	}

	/**
	 * 插入数据
	 */
	private void insertData(String tempName) {
		db = helper.getWritableDatabase();
		db.execSQL("insert into records(name) values('" + tempName + "')");
		db.close();
	}

	/**
	 * 模糊查询数据
	 */
	private void queryData(String tempName) {
		Cursor cursor = helper.getReadableDatabase().rawQuery(
				"select id as _id,name from records where name like '%"
						+ tempName + "%' order by id desc ", null);
		// 创建adapter适配器对象
		dbadapter = new SimpleCursorAdapter(this, R.layout.item_luntan_saeer,
				cursor, new String[] { "name" }, new int[] { R.id.luntanName },
				CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
		// 设置适配器
		listView.setAdapter(dbadapter);
		dbadapter.notifyDataSetChanged();
	}

	/**
	 * 检查数据库中是否已经有该条记录
	 */
	private boolean hasData(String tempName) {
		Cursor cursor = helper.getReadableDatabase().rawQuery(
				"select id as _id,name from records where name =?",
				new String[] { tempName });
		// 判断是否有下一个
		return cursor.moveToNext();
	}

	/**
	 * 清空数据
	 */
	private void deleteData() {
		db = helper.getWritableDatabase();
		db.execSQL("delete from records");
		db.close();
	}

	class LuntanSearAdapter extends BaseAdapter {
		Context context;
		List<WeChaReMenBean> list;

		public LuntanSearAdapter(Context context, List<WeChaReMenBean> list) {
			// TODO Auto-generated constructor stub
			this.list = list;
			this.context = context;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			ViewHouder houder;
			if (convertView == null) {
				houder = new ViewHouder();
				convertView = LayoutInflater.from(context).inflate(
						R.layout.adapter_mygridview_item, null);
				houder.textView = (TextView) convertView
						.findViewById(R.id.text_item);
				convertView.setTag(houder);
			} else {
				houder = (ViewHouder) convertView.getTag();
			}
			houder.textView.setText(list.get(position).getName());
			return convertView;
		}

		class ViewHouder {
			TextView textView;
		}

	}

}
